package com.base.cn.platform.os.interceptor;

import com.base.cn.platform.os.common.constants.CommonConstants;
import com.base.cn.platform.os.common.j2cache.CustomCacheChannel;
import com.base.cn.platform.os.common.j2cache.J2CacheRegion;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.common.utils.web.WebMobileLoginUtil;
import com.base.cn.platform.os.common.utils.web.WebUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Map;

/**
 * 前台用户登录拦截
 *
 * @author s.li
 * @create 2018-05-30-9:18
 */
@Slf4j
public class MobileUserLoginInterceptor implements HandlerInterceptor {

    private Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();

    @Autowired
    private WebMobileLoginUtil webMobileLoginUtil;
    @Autowired
    private CustomCacheChannel customCacheChannel;
    @Autowired
    private Environment environment;
    @Autowired
    private SignCheck signCheck;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求类型
        JsonObject user = webMobileLoginUtil.getLoginUser(request);
        if(user==null){

            if(ObjectUtils.isNotEmpty(request.getParameter("noMobile"))){
                if(simulateLogin(request, response)){
                    return true;
                }else {
                    response.sendRedirect("/mobile/cash/appError");
                    return false;
                }
            }
            notLoginRedirect(request,response);
            return false;
        }else{
            String msid = WebUtils.getCookie(request,CommonConstants.MOBILE_USER_SINGLE_ID);
            log.info("====================msid:"+msid);
            String userId = user.get("id").getAsString();
            String token = (String)customCacheChannel.get(J2CacheRegion.THIRTY_DAY_REGION.getKey(),userId).getValue();
            log.info("====================token:"+token);
            if(StringUtils.isEmpty(token) || StringUtils.isEmpty(msid) || !msid.equals(token)){
                if(StringUtils.isNotEmpty(msid)){
                    customCacheChannel.evict(J2CacheRegion.THIRTY_DAY_REGION.getKey(),msid);
                    customCacheChannel.evict(J2CacheRegion.ONE_DAY_REGION.getKey(),msid);
                }
                notLoginRedirect(request,response);
                return false;
            }
        }
        return true;
    }

    /**
     * 未登录跳转
     * @param request
     * @param response
     * @throws Exception
     */
    private void notLoginRedirect(HttpServletRequest request,HttpServletResponse response) throws Exception{
        String accept = request.getHeader("accept");
        String requestURL = WebUtils.getCompleteUrl(request);
        if(WebUtils.isAjaxRequest(request) && accept.toLowerCase().contains("json")){
            requestURL = request.getHeader("referer");
        }
        if(StringUtils.isNotEmpty(requestURL)){
            WebUtils.setCookie(response, CommonConstants.REDIRECT,requestURL,1);
        }
        if(WebUtils.isAjaxRequest(request) && accept.toLowerCase().contains("json")){
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(gson.toJson(ResultUtil.ERROR("还未登录，请去登录")));
        }else{
            if(ObjectUtils.isNotEmpty(WebUtils.getCookie(request,"noMobile"))&&StringUtils.isNotEmpty(WebUtils.getCookie(request,"noMobile"))){
                response.sendRedirect("/mobile/cash/appError");
            }else{
                response.sendRedirect("/mobile/user/login");

            }
        }
    }

    /**
     * 对app进行模拟登录
     * @param request
     * @param response
     * @return
     */
        private Boolean simulateLogin(HttpServletRequest request, HttpServletResponse response){
        //验证密钥
            String privateKey = environment.getProperty("app.private.key");
            //验证密钥
            boolean s = signCheck.checkPrivateKey(request,privateKey);
            if(!s){
                log.warn("====================接口密钥错误");
                return false;
            }
            s = signCheck.signCheck(request);
            if(!s){
                log.warn("====================接口签名错误");
                return false;
            }

        String _token = request.getParameter("token");
        String userId = request.getParameter("userId");
        String token = (String)customCacheChannel.get(J2CacheRegion.THIRTY_DAY_REGION.getKey(),userId).getValue();
        //验证是否登录
        if(_token.equals(token)){
            WebUtils.setCookie(response,CommonConstants.MOBILE_USER_SINGLE_ID,token,1);
            WebUtils.setCookie(response,CommonConstants.NO_MOBILE,request.getParameter("noMobile"),1);
            return true;
        }else{
            log.warn("====================token:"+token);
            log.warn("====================_token:"+_token);
            log.warn("====================token错误");
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {

    }
}
